<?php


class MyPdo{
	private static $obj = null;
	public $p = '';
	private $host;
	private $db;
	private $root;
	private $pwd;

	public static function init($host='',$db='',$root='',$pwd=''){
		if(MyPdo::$obj == null){
			self::$obj = new MyPdo($host,$db,$root,$pwd);
		}
		return self::$obj;
	}

	private function __construct($host='',$db='',$root='',$pwd=''){
		global $config;
		if($host){
			$this->host = $host;
		}else{
			$this->host = $config['db_host'];
		}
		if($db){
			$this->db = $db;
		}else{
			$this->db = $config['db_name'];
		}
		if($root){
			$this->root = $root;
		}else{
			$this->root = $config['db_user'];
		}
		if($pwd){
			$this->pwd = $pwd;
		}else{
			$this->pwd = $config['db_pwd'];
		}
		
		if($this->p == ''){
			try{
				$this->p = new PDO("mysql:host={$this->host};dbname={$this->db}","{$this->root}","$this->pwd");
				$this->p->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
				$this->p->query("set names utf8");
				return $this->p;
			}catch(PDOException $e){
				die('数据库连接失败'.$e->getMessage());
			}
		}
	}

	/*
		@查询操作
		@parm 	$sql (string)	sql语句
		@parm 	$arr (Array)	索引数组形式的参数	
		@parm 	$type 	string	查询单条或多条，默认false查询多条,true为查询单条
		@return
	*/
	public function dql($sql,$arr,$type=false){
		$st = $this->p->prepare($sql);
		$st->execute($arr);
		if(!$type){
			$res = $st->fetchAll(PDO::FETCH_ASSOC);
		}else{
			$res = $st->fetch(PDO::FETCH_ASSOC);
		}
		if($res){
			return $res;
		}else{
			return false;
		}
	}




	/*
		@增删改操作
		@parm 	$sql (string)	sql语句
		@parm 	$arr (Array)	索引数组形式的参数
		@return  
				添加操作成功时返回最后添加的id
				删除操作成功时返回受影响的行数
				修改操作成功时返回受影响的行数
				操作失败时返回false
	*/
	public function dml($sql,$arr){
		$st = $this->p->prepare($sql);
		$st->execute($arr);
		if($this->p->lastInsertId() > 0){
			return $this->p->lastInsertId();
		}else if($st->rowCount() > 0){
			return $st->rowCount();
		}else{
			return false;
		}
	}

}













